<template>
  <div class="error-book">
    <h1 class="page-title">我的错题本</h1>
    
    <!-- 筛选和排序工具栏 -->
    <div class="toolbar">
      <div class="filter-section">
        <el-select v-model="subjectFilter" placeholder="选择学科" clearable>
          <el-option
            v-for="item in subjects"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        
        <el-select v-model="dateFilter" placeholder="时间范围" clearable>
          <el-option label="最近一周" value="week"></el-option>
          <el-option label="最近一月" value="month"></el-option>
          <el-option label="最近三月" value="quarter"></el-option>
          <el-option label="全部时间" value="all"></el-option>
        </el-select>
        
        <el-select v-model="errorTypeFilter" placeholder="错误类型" clearable>
          <el-option label="概念理解错误" value="concept"></el-option>
          <el-option label="计算错误" value="calculation"></el-option>
          <el-option label="应用错误" value="application"></el-option>
          <el-option label="其他错误" value="other"></el-option>
        </el-select>
      </div>
      
      <div class="action-section">
        <el-button type="primary" @click="refreshErrorList">刷新</el-button>
        <el-button type="success" @click="exportErrorBook">导出错题本</el-button>
      </div>
    </div>
    
    <!-- 错题统计卡片 -->
    <el-card class="statistics-card">
      <div class="statistics-grid">
        <div class="statistic-item">
          <div class="statistic-value">{{ totalErrors }}</div>
          <div class="statistic-label">错题总数</div>
        </div>
        <div class="statistic-item">
          <div class="statistic-value">{{ resolvedErrors }}</div>
          <div class="statistic-label">已解决</div>
        </div>
        <div class="statistic-item">
          <div class="statistic-value">{{ unresolvedErrors }}</div>
          <div class="statistic-label">未解决</div>
        </div>
        <div class="statistic-item">
          <div class="statistic-value">{{ mostErrorSubject }}</div>
          <div class="statistic-label">最多错题学科</div>
        </div>
      </div>
    </el-card>
    
    <!-- 错题列表 -->
    <div class="error-list">
      <el-card v-for="(error, index) in filteredErrors" :key="index" class="error-card">
        <div class="error-header">
          <div class="error-meta">
            <el-tag size="small" type="info">{{ getSubjectName(error.subjectId) }}</el-tag>
            <el-tag size="small" :type="isResolved(error) ? 'success' : 'danger'">
              {{ isResolved(error) ? '已解决' : '未解决' }}
            </el-tag>
            <span class="error-date">{{ formatDate(error.date) }}</span>
          </div>
          <div class="error-actions">
            <el-button 
              size="small" 
              :type="isResolved(error) ? 'info' : 'success'"
              @click="toggleErrorStatus(error)">
              {{ isResolved(error) ? '标记为未解决' : '标记为已解决' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteError(error)">删除</el-button>
          </div>
        </div>
        
        <div class="error-content">
          <div class="question-section">
            <h3>题目内容</h3>
            <div class="question-content" v-html="error.question"></div>
          </div>
          
          <div class="answer-section">
            <div class="my-answer">
              <h4>我的答案</h4>
              <div v-html="error.myAnswer"></div>
            </div>
            <div class="correct-answer">
              <h4>正确答案</h4>
              <div v-html="error.correctAnswer"></div>
            </div>
          </div>
          
          <div class="error-analysis">
            <h3>错误分析</h3>
            <div v-html="error.analysis"></div>
          </div>
          
          <div class="error-notes" v-if="error.notes">
            <h3>我的笔记</h3>
            <div v-html="error.notes"></div>
          </div>
        </div>
        
        <div class="error-footer">
          <el-button size="small" @click="showNoteEditor(error)">
            {{ error.notes ? '编辑笔记' : '添加笔记' }}
          </el-button>
          <el-button size="small" type="primary" @click="practiceRelated(error)">
            练习相似题目
          </el-button>
        </div>
      </el-card>
      
      <div v-if="filteredErrors.length === 0" class="empty-state">
        <el-empty description="暂无错题记录">
          <el-button type="primary" @click="goToPractice">去练习</el-button>
        </el-empty>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination-container" v-if="filteredErrors.length > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalErrors"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
    
    <!-- 笔记编辑对话框 -->
    <el-dialog
      v-model="noteDialogVisible"
      title="编辑笔记"
      width="50%">
      <el-form>
        <el-form-item>
          <el-input
            v-model="currentNote"
            type="textarea"
            rows="6"
            placeholder="在这里记录你对这道题的理解和解题思路...">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="noteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNote">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { ElLoading } from 'element-plus';

const router = useRouter();

// 筛选状态
const subjectFilter = ref('');
const dateFilter = ref('');
const errorTypeFilter = ref('');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 错题笔记对话框
const noteDialogVisible = ref(false);
const currentNote = ref('');
const currentErrorIndex = ref(null);

// 学科列表
const subjects = ref([
  { id: 1, name: '语文' },
  { id: 2, name: '数学' },
  { id: 3, name: '英语' },
  { id: 4, name: '物理' },
  { id: 5, name: '化学' },
  { id: 6, name: '生物' },
]);

// 模拟数据
const errors = ref([]);

// 统计信息计算
// 错题总数是student_answer与correct_answer不一致的数据数量
// 在后端SQL查询中已经过滤，只返回了不一致的数据
const totalErrors = computed(() => errors.value.length);
// 已解决的错题
const resolvedErrors = computed(() => errors.value.filter(e => isResolved(e)).length);
// 未解决的错题
const unresolvedErrors = computed(() => errors.value.filter(e => !isResolved(e)).length);

// 找出错题最多的学科
const mostErrorSubject = computed(() => {
  const subjectCounts = {};
  errors.value.forEach(error => {
    if (subjectCounts[error.subjectId]) {
      subjectCounts[error.subjectId]++;
    } else {
      subjectCounts[error.subjectId] = 1;
    }
  });
  
  let maxCount = 0;
  let maxSubjectId = null;
  
  for (const [subjectId, count] of Object.entries(subjectCounts)) {
    if (count > maxCount) {
      maxCount = count;
      maxSubjectId = subjectId;
    }
  }
  
  if (maxSubjectId) {
    const subject = subjects.value.find(s => s.id === parseInt(maxSubjectId));
    return subject ? subject.name : '未知';
  }
  
  return '无';
});

// 筛选错题
const filteredErrors = computed(() => {
  // 根据学科筛选
  let filtered = errors.value;
  
  if (subjectFilter.value) {
    filtered = filtered.filter(error => error.subjectId === subjectFilter.value);
  }
  
  // 根据时间筛选
  if (dateFilter.value) {
    const now = new Date();
    let startDate;
    
    switch (dateFilter.value) {
      case 'week':
        startDate = new Date(now.setDate(now.getDate() - 7));
        break;
      case 'month':
        startDate = new Date(now.setMonth(now.getMonth() - 1));
        break;
      case 'quarter':
        startDate = new Date(now.setMonth(now.getMonth() - 3));
        break;
      default:
        startDate = null;
    }
    
    if (startDate) {
      filtered = filtered.filter(error => new Date(error.date) >= startDate);
    }
  }
  
  // 根据错误类型筛选
  if (errorTypeFilter.value) {
    filtered = filtered.filter(error => getErrorTypeFromKnowledgePoint(error.knowledgePoint) === errorTypeFilter.value);
  }
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  
  return filtered.slice(start, end);
});

// 获取学科名称
const getSubjectName = (subjectId) => {
  const subject = subjects.value.find(s => s.id === subjectId);
  return subject ? subject.name : '未知学科';
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 获取错题数据
const fetchErrors = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载错题中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  try {
    const subjectParam = subjectFilter.value ? `?subject=${subjectFilter.value}` : '';
    const response = await axios.get(`/api/student/mistake-collection${subjectParam}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data) {
      errors.value = response.data.map(item => ({
        id: item.id,
        subjectId: item.subject,
        question: item.content,
        myAnswer: item.studentAnswer || '未作答',
        correctAnswer: item.correctAnswer,
        analysis: item.analysis || '暂无解析',
        date: item.lastMistakeTime,
        mistakeCount: item.mistakeCount,
        notes: '',
        knowledgePoint: item.knowledgePoint
      }));
      
      console.log('错题数据:', response.data);
    }
  } catch (error) {
    console.error('获取错题数据失败:', error);
    ElMessage.error('获取错题数据失败，请稍后重试');
  } finally {
    loading.close();
  }
};

// 刷新错题列表
const refreshErrorList = () => {
  fetchErrors();
};

// 删除错题
const deleteError = async (error) => {
  ElMessageBox.confirm('确定要删除这道错题吗？删除后将无法恢复。', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/student/mistake-collection/${error.id}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      errors.value = errors.value.filter(e => e.id !== error.id);
      ElMessage.success('删除成功');
    } catch (err) {
      console.error('删除错题失败:', err);
      ElMessage.error('删除错题失败，请稍后重试');
    }
  }).catch(() => {});
};

// 标记错题状态
const toggleErrorStatus = async (error) => {
  try {
    const newStatus = !isResolved(error);
    await axios.put(`/api/student/mistake-collection/${error.id}/status`, {
      resolved: newStatus
    }, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    // 直接更新本地状态
    error.mistakeCount = newStatus ? 0 : 1;
    ElMessage.success(`已${newStatus ? '标记为已解决' : '标记为未解决'}`);
    
    console.log(`已将错题ID: ${error.id} 的状态更新为: ${newStatus ? '已解决' : '未解决'}`);
    
    // 刷新错题列表 - 这可能会导致当前显示的错题被过滤掉
    if (newStatus) {
      setTimeout(() => {
        fetchErrors(); // 如果设为已解决，延迟刷新列表
      }, 2000);
    }
  } catch (err) {
    console.error('更新错题状态失败:', err);
    ElMessage.error('更新错题状态失败，请稍后重试');
  }
};

// 显示笔记编辑器
const showNoteEditor = (error) => {
  currentErrorIndex.value = errors.value.findIndex(e => e.id === error.id);
  currentNote.value = error.notes || '';
  noteDialogVisible.value = true;
};

// 保存笔记
const saveNote = () => {
  if (currentErrorIndex.value !== null) {
    errors.value[currentErrorIndex.value].notes = currentNote.value;
    ElMessage.success('笔记保存成功');
    noteDialogVisible.value = false;
  }
};

// 练习相似题目
const practiceRelated = (error) => {
  ElMessage.success('即将生成相似题目练习');
  router.push({
    path: '/student/practice',
    query: { relatedTo: error.id, subjectId: error.subjectId }
  });
};

// 根据学科名称获取学科ID
const getSubjectIdByName = (subjectName) => {
  const subject = subjects.value.find(s => s.name === subjectName);
  return subject ? subject.id : 1; // 默认返回ID为1
};

// 根据知识点推断错误类型
const getErrorTypeFromKnowledgePoint = (knowledgePoint) => {
  if (!knowledgePoint) return 'other';
  
  const lowerKP = knowledgePoint.toLowerCase();
  if (lowerKP.includes('概念') || lowerKP.includes('定义')) {
    return 'concept';
  } else if (lowerKP.includes('计算') || lowerKP.includes('运算')) {
    return 'calculation';
  } else if (lowerKP.includes('应用') || lowerKP.includes('实践')) {
    return 'application';
  }
  return 'other';
};

// 导出错题本
const exportErrorBook = async () => {
  try {
    const response = await axios.get('/api/student/mistake-collection/export', {
      responseType: 'blob',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '错题本.pdf');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (err) {
    console.error('导出错题本失败:', err);
    ElMessage.error('导出错题本失败，请稍后重试');
  }
};

// 去练习页面
const goToPractice = () => {
  router.push('/student/practice');
};

// 处理分页
const handlePageChange = (page) => {
  currentPage.value = page;
  // 实际项目中应该调用API获取对应页的数据
};

// 根据mistakeCount判断是否已解决
function isResolved(error) {
  return error.mistakeCount === 0;
}

onMounted(() => {
  fetchErrors();
});
</script>

<style scoped>
.error-book {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-section {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.statistics-card {
  margin-bottom: 20px;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.statistic-item {
  text-align: center;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #1a73e8;
  margin-bottom: 5px;
}

.statistic-label {
  color: #606266;
}

.error-card {
  margin-bottom: 20px;
}

.error-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.error-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.error-date {
  color: #909399;
  font-size: 14px;
}

.error-content {
  margin-bottom: 15px;
}

.question-section {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.question-section h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.answer-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin-bottom: 15px;
}

.my-answer, .correct-answer {
  padding: 15px;
  border-radius: 6px;
}

.my-answer {
  background-color: #fef0f0;
}

.correct-answer {
  background-color: #f0f9eb;
}

.my-answer h4, .correct-answer h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.error-analysis {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #ecf5ff;
  border-radius: 6px;
}

.error-analysis h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.error-notes {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f4f4f5;
  border-radius: 6px;
}

.error-notes h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.error-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.empty-state {
  margin: 40px 0;
  text-align: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
  }
  
  .filter-section {
    margin-bottom: 15px;
  }
  
  .answer-section {
    grid-template-columns: 1fr;
  }
}
</style> 